<?php
/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

/*
@$ftmp = $_FILES['file']['tmp_name'];
@$fname = $_FILES['file']['name'];
@$fsize = $_FILES['file']['size'];
@$ftype = $_FILES['file']['type'];
@$ferror = $_FILES[$fileid]['error'];
*/

// Requires full filename
//define("CHECKFILE",ROOT_PATH."bash/checkfile.sh");
define("CHECKFILE",ROOT_PATH."bash/checkupload.py");
define("RWHEADER",ROOT_PATH."bash/fixheader.py"); 

switch ($ferror) {
	case UPLOAD_ERR_INI_SIZE:
		$error = s("The uploaded file exceeds the max size allowed.");
		break;
	case UPLOAD_ERR_FORM_SIZE:
		$error = s("The uploaded file exceeds the max size allowed.");
		break;
	case UPLOAD_ERR_PARTIAL:
		$error = s("The uploaded file was only partially uploaded.");
		break;
	case UPLOAD_ERR_NO_FILE:
		$error = s("No file was uploaded.");
		break;
	case UPLOAD_ERR_NO_TMP_DIR:
		$error = s("Missing a temporary folder.");
		break;
	case UPLOAD_ERR_CANT_WRITE:
		$error = s("Failed to write file to disk.");
		break;
	case UPLOAD_ERR_EXTENSION:
		$error = s("File upload stopped by extension.");
		break;		
	case UPLOAD_ERR_OK:
		break;
	default:
		$error = s("Unknown error.");
		break;
}
$_log->debug("----------------------------------");
$PJID=$param['pid'];
/* normalize the id. with fixed length and better chars for filename*/
$UID= util::encrypt($param['id']);

$ts = new teamsetting;
$ts->teamid = getTeamId($CURRENT_USER);
$ts->id=RPL_HEADER;
if ($loader->get($ts)) {
	$headermsg = $ts->value;
} else {
	$headermsg=false;
}

if(!isset($error) and isset($ftmp)) {
	$ufid = util::hashcode($fname.$UID);
	$temp_filename = TEMP_PATH."/".$ufid."_".$fname;
	$tempset_path = TEMP_PATH."/".$ufid; 
	$fileset_path = TEMP_PATH."/".$UID;
	
	if (!file_exists(TEMP_PATH)) {
		createDir(TEMP_PATH);
	}
	
	if (!file_exists($fileset_path)) {
		createDir($fileset_path);
	}

	if (file_exists($tempset_path)) {
		deltree($tempset_path);
	} 
	createDir($tempset_path);	

	move_uploaded_file($ftmp,$temp_filename);

	$fileok=false;
	$_log->info("Uploaded file: ".$fname." [$ftype]");
	$isStream = in_array($ftype,util::stringToArray(TYPE_FILE_STREAM));
	$fileinfo = pathinfo($fname);
	if ($fileinfo['extension']=="po" && $isStream) {
		$_log->warn("File extension is .po and is identified as archive. Forcing text.");
		$isStream = false;
	}
	
	if ($isStream) {
		$_log->debug("File identified as archive");
		$tar = new Archive_Tar($temp_filename);
		if ($tar->extract($tempset_path)) {
			$fileok = true;	
		} else {
			$error =  s("Invalid file format");
		}
		unset($tar);
		unlink($temp_filename);
	} else {
		$_log->debug("File identified as text");
		if (rename($temp_filename,$tempset_path."/".$fname)) {
			$fileok=true;
		} else {
			$error =  String::format(s("Error with uploaded file. TransId: {0}"),$TRANSID);
		}
	}

	if ($fileok) {
		$team = new team;
		$team->id=getTeamId($CURRENT_USER);
		$loader->get($team);
		
		$prj = new project;
		$prj->id=$PJID;
		$subplist = $loader->loadListBy($prj,$prj->listSubProjects());

		$upload = new upload;
		$upload->id=$UID;
		$r = $loader->get($upload);
		
		if (!$r) {
			$upload->userid=$CURRENT_USER->userid;
			$upload->projectid=$PJID;
			$upload->teamid=getTeamId($CURRENT_USER);
			$loader->save($upload);
		}

		$dir=opendir($tempset_path);
		$error ="";
		while ($item = readdir($dir)) {
			$errmsg="";
			$itemfile = $tempset_path."/".$item;
			if (is_file($itemfile) && is_readable($itemfile)) {
				$file = new files($PJID);
				$file->name=$item;
				$file->teamid=getTeamId($CURRENT_USER);
				$list = $loader->loadListBy($file,$file->findFile());
				$_log->debug("Search [$item]. Count ".count($list));
				$step=0;
				if (count($list)>0) {
					$step=1;
					foreach ($list as $file) {
						if ($file->userid == $CURRENT_USER->userid || $file->userid2 == $CURRENT_USER->userid) {
							$step=2;
							switch ($CURRENT_USER->userid) {
								case $file->userid:
									if ($file->statusid!=FILE_STATUS_TRANS && $file->statusid!=FILE_STATUS_LOCKED && $file->statusid!=FILE_STATUS_CHKPND && $file->statusid!=FILE_STATUS_DONE) {
										$errmsg=String::format(s("Set status to '{0}' to upload this file."),s("Translating"));
									} else {
										$errmsg="";
										$step=3;
									}
									break;
								case $file->userid2:
									if ($file->statusid!=FILE_STATUS_PROOF && $file->statusid!=FILE_STATUS_CHKPND) {
										$errmsg=String::format(s("Set status to '{0}' to upload this file."),s("Proofreading"));
									} else {
										$errmsg="";
										$step=3;
									}
									break;
								default:
									$errmsg=s("Unknown file state.");
									break;
							}
							/*
							if ($file->statusid!=FILE_STATUS_TRANS && $file->statusid!=FILE_STATUS_PROOF) {
								$errmsg=s("The file is not in the correct status to be uploaded");
							} elseif (($file->userid==$CURRENT_USER->userid && $file->statusid==FILE_STATUS_PROOF)) {
								$errmsg=s("The file is locked by the reviewer");
							} elseif (($file->userid==$CURRENT_USER->userid2 && $file->statusid==FILE_STATUS_TRANS)) {
								$errmsg=s("The file is locked by the translator");
							} else {
								$errmsg="";
								$step=3;
								break;
							}*/
						}
					}
					if ($step==1) {
						$errmsg=s("You are not the translator nor the reviewer of this file.");
					}
				} else {
					$errmsg=s("File not found in project.");
				}

				if ($step == 3) {
					$ret = false;
					$chkres=array();
					$execret = 0;
					$_log->debug("Checking file $itemfile");
					@exec(CHECKFILE." ".$itemfile,$chkres,$execret);
					if ($execret==1) {
						$_log->info("File contains errors.");
						$_log->debug($chkres);
						$errmsg="";
						foreach ($chkres as $m) {
							if ($errmsg!="") $errmsg.="<br>";
							$errmsg.=$m;
						}
						$errmsg = str_replace($tempset_path."/","",$errmsg);
						$errmsg = jsAddSlashes(jsAddSlashes($errmsg));
					} else if ($execret!=0) {
						$_log->error("Shell error. Return code [$execret]");
						if ($execret==126) {
							$_log->error("Probably permission denied");
						}
						$errmsg=s("Unable to check file. Contact the administrator.")." [$TRANSID]";
					} else {
						$ret = true;
					}

					if ($ret) {
						$langpath = str_replace('$LANG',$team->lang,$subplist[$file->prjid]->path);
						// COULD CHECK FILE STATS HERE
						$dest_path = $fileset_path."/".$langpath; 
						if (!file_exists($dest_path)) {
							if (!mkdir($dest_path,0777,true)) {
								$_log->error("Failed to create ".$dest_path);
							}
						}
						if ($headermsg!==false) {
							// REWRITE FILE HEADER
							$_log->debug("Rewrite header: ".$headermsg);
							@exec(RWHEADER." ".$itemfile." \"".$headermsg."\"",$chkres,$execret);
						}
						if (copy($itemfile,$dest_path."/".$item)) {
							$step=4;
						} else {
							$_log->error("Failed to copy ".$itemfile);
							$errmsg=s("Failed to copy file. If this problem persist, contact the administrator.")." [$TRANSID]";
						}
					}
				}

				$updata = new upload_data;
				$updata->objid=$UID;
				$updata->name=$file->name;
				$updata->path=$subplist[$file->prjid]->name;
				$updata->pjid=$file->prjid;
				$updata->filestatus=$file->statusid;
				$updata->fileid=$step > 1 ? $file->id : "0";
				$updata->statusid=$step == 4 ? FILE_UPLOAD_OK : FILE_UPLOAD_FAIL;
				$updata->msg=$errmsg;
				$loader->save($updata);
				
				$_log->info("$file->name DONE");
				$_log->debug("$UID - $file->name [$updata->statusid - $errmsg]");
			} else {
				if ($item!="." && $item!="..") {
					if ($error=="") {
						$error=s("Error reading the file")." ".$item;
					} else {
						$error.=", ".$item;
					}
					$_log->error("Error reading ".$item);
					$_log->error("Directory dump: ".util::arrayToString(scandir($tempset_path)));
				}
			}
		}
		closedir($dir);
	} else {
		$_log->error($error);
	}
	
	deltree($tempset_path);
	if (file_exists($tempset_path)) {
		if (!rmdir($tempset_path)) {
			$_log->warn("Unable to remove $tempset_path");
		}
	}
		
} else {
	$_log->error("Upload failed [$ferror].".$error);
}
 
?>
